import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hao/page/home/AddRecordPage.dart';
import 'package:hao/page/home/HomeViewModel.dart';
import 'package:hao/utils/ColorUtil.dart';
import 'package:hao/utils/HaoModel.dart';
import 'package:hao/utils/RecordModel.dart';
import 'package:hao/utils/Utils.dart';
import 'package:loading_indicator/loading_indicator.dart';
import 'package:sprintf/sprintf.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  HomeViewModel _viewModel = Get.put(HomeViewModel());

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: const Text("租用列表"),
      ),
      body: Obx(() => _viewModel.list.isEmpty
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    "images/icon.png",
                    width: 100,
                  ),
                  const SizedBox(
                    height: 20,
                  ),
                  const Text(
                    "租用列表为空",
                    style: TextStyle(fontSize: 20),
                  )
                ],
              ),
            )
          : ListView(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              children: _viewModel.list
                  .map((element) => _parentWidget(element))
                  .toList(),
            )),
    );
  }

  Widget _parentWidget(Map map) {
    String month = map["month"];
    List datas = map["datas"];
    int totalPrice = 0;
    for (Record chu in datas) {
      int price = int.parse(chu.price ?? "0");
      totalPrice += price;
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            RichText(
                text: TextSpan(
                    text: sprintf("%02d", [int.parse(month)]),
                    style: TextStyle(
                        fontSize: 25,
                        fontWeight: FontWeight.w700,
                        color: Get.theme.primaryColorDark),
                    children: const [
                  TextSpan(
                    text: " 月",
                    style: TextStyle(fontSize: 13, fontWeight: FontWeight.w700),
                  ),
                ])),
            Text(
              "共花费￥$totalPrice",
              style: const TextStyle(fontSize: 13),
            ),
          ],
        ),
        const SizedBox(
          height: 10,
        ),
        Column(
          children: datas.map((e) => _itemWidget(e)).toList(),
        ),
        const SizedBox(
          height: 10,
        ),
      ],
    );
  }

  Widget _itemWidget(Record chu) {
    String remark = chu.remark ?? "";

    return GestureDetector(
      onTap: () {
        Get.to(() => AddRecordPage(
              chu: chu,
            ))?.then((value) {
          if (value != null) {
            _viewModel.loadData();
          }
        });
      },
      child: Container(
        margin: const EdgeInsets.only(bottom: 15),
        padding: const EdgeInsets.all(10),
        decoration: BoxDecoration(
            color: Get.theme.primaryColor,
            borderRadius: BorderRadius.circular(10),
            boxShadow: [haoBoxShadow()]),
        child: Stack(
          alignment: Alignment.centerRight,
          children: [
            Row(
              children: [
                const SizedBox(
                  width: 10,
                ),
                Expanded(
                    child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      chu.title ?? "",
                      style: const TextStyle(
                          fontSize: 16, fontWeight: FontWeight.w700),
                    ),
                    Container(
                      height: 26,
                      alignment: Alignment.centerLeft,
                      child: Text(
                          "时长：${durationStr(chu.time ?? "", chu.expire ?? "")}",
                          style: const TextStyle(
                            fontSize: 13,
                          )),
                    ),
                    Container(
                      height: 26,
                      alignment: Alignment.centerLeft,
                      child: Text("开始时间：${chu.time}",
                          style: const TextStyle(
                            fontSize: 13,
                          )),
                    ),
                    Container(
                      height: 26,
                      alignment: Alignment.centerLeft,
                      child: Text("到期时间：${chu.expire}",
                          style: const TextStyle(
                            fontSize: 13,
                          )),
                    ),
                    remark.isEmpty
                        ? const SizedBox()
                        : Column(
                            children: [
                              const SizedBox(
                                height: 5,
                              ),
                              Text("备注：${chu.remark ?? ""}",
                                  style: const TextStyle(
                                    fontSize: 13,
                                  ))
                            ],
                          ),
                  ],
                )),
                Column(
                  children: [
                    Text(
                      "￥${chu.price}",
                      style: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w700,
                          color: MAIN_COLOR),
                    ),
                    const SizedBox(
                      height: 30,
                    ),
                    Text(
                      diffTimeStr(chu.expire ?? ""),
                      style: const TextStyle(color: Colors.red),
                    )
                  ],
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  String diffTimeStr(String endTime) {
    String str = "";
    DateTime end = DateTime.parse(endTime);
    if (end.isBefore(DateTime.now())) {
      str = "已过期";
    } else {
      Duration duration = end.difference(DateTime.now());
      int hour = duration.inHours;

      int day = (hour / 24.0).floor();
      int diff = hour - day * 24;
      if (day != 0) {
        str += "$day天";
      }
      if (diff != 0) {
        str += "$diff小时";
      }
    }
    return str;
  }

  String durationStr(String startTime, String endTime) {
    String str = "";
    DateTime start = DateTime.parse(startTime);
    DateTime end = DateTime.parse(endTime);
    Duration duration = end.difference(start);
    int hour = duration.inHours;

    int day = (hour / 24.0).floor();
    int diff = hour - day * 24;
    if (day != 0) {
      str += "$day天";
    }
    if (diff != 0) {
      str += "$diff小时";
    }

    return str;
  }

  @override
  bool get wantKeepAlive => true;
}
